Open In Colab DSPy는 LM 프롬프트와 가중치를 알고리즘적으로 최적화하기 위한 프레임워크로, 특히 LM이 파이프라인 내에서 한 번 이상 사용될 때 유용합니다. Weave는 DSPy 모듈과 함수를 사용하여 이루어진 호출을 자동으로 추적하고 기록합니다.

추적

개발 중이나 프로덕션 환경에서 언어 모델 애플리케이션의 추적을 중앙 위치에 저장하는 것이 중요합니다. 이러한 추적은 디버깅에 유용하며, 애플리케이션을 개선하는 데 도움이 되는 데이터셋으로 활용될 수 있습니다. Weave는 다음에 대한 추적을 자동으로 캡처합니다 DSPy. 추적을 시작하려면, weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>") 호출하고 라이브러리를 평소처럼 사용하세요.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

lm = dspy.LM('openai/gpt-4o-mini')
dspy.configure(lm=lm)
classify = dspy.Predict("sentence -> sentiment")
classify(sentence="it's a charming and often affecting journey.")
dspy_trace.png Weave는 DSPy 프로그램의 모든 LM 호출을 기록하여 입력, 출력 및 메타데이터에 대한 세부 정보를 제공합니다.

자신만의 DSPy 모듈 및 시그니처 추적하기

A Module는 프롬프팅 기법을 추상화하는 학습 가능한 매개변수가 있는 DSPy 프로그램의 구성 요소입니다. A Signature는 DSPy 모듈의 입력/출력 동작에 대한 선언적 명세입니다. Weave는 DSPy 프로그램의 모든 내장 및 사용자 정의 시그니처와 모듈을 자동으로 추적합니다.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

class Outline(dspy.Signature):
    """Outline a thorough overview of a topic."""

    topic: str = dspy.InputField()
    title: str = dspy.OutputField()
    sections: list[str] = dspy.OutputField()
    section_subheadings: dict[str, list[str]] = dspy.OutputField(
        desc="mapping from section headings to subheadings"
    )


class DraftSection(dspy.Signature):
    """Draft a top-level section of an article."""

    topic: str = dspy.InputField()
    section_heading: str = dspy.InputField()
    section_subheadings: list[str] = dspy.InputField()
    content: str = dspy.OutputField(desc="markdown-formatted section")


class DraftArticle(dspy.Module):
    def __init__(self):
        self.build_outline = dspy.ChainOfThought(Outline)
        self.draft_section = dspy.ChainOfThought(DraftSection)

    def forward(self, topic):
        outline = self.build_outline(topic=topic)
        sections = []
        for heading, subheadings in outline.section_subheadings.items():
            section, subheadings = (
                f"## {heading}",
                [f"### {subheading}" for subheading in subheadings],
            )
            section = self.draft_section(
                topic=outline.title,
                section_heading=section,
                section_subheadings=subheadings,
            )
            sections.append(section.content)
        return dspy.Prediction(title=outline.title, sections=sections)


draft_article = DraftArticle()
article = draft_article(topic="World Cup 2002")

DSPy 프로그램의 최적화 및 평가

Weave는 또한 DSPy 최적화 도구 및 평가 호출에 대한 추적을 자동으로 캡처하여 개발 세트에서 DSPy 프로그램의 성능을 개선하고 평가하는 데 사용할 수 있습니다.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"
weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

def accuracy_metric(answer, output, trace=None):
    predicted_answer = output["answer"].lower()
    return answer["answer"].lower() == predicted_answer

module = dspy.ChainOfThought("question -> answer: str, explanation: str")
optimizer = dspy.BootstrapFewShot(metric=accuracy_metric)
optimized_module = optimizer.compile(
    module, trainset=SAMPLE_EVAL_DATASET, valset=SAMPLE_EVAL_DATASET
)